import json
import time

from celery.bin.result import result
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from redis.lock import Lock

from carts.views import CartView
from dadashop import settings
from goods.models import SKU
from orders.models import OrderInfo, OrderGoods
from user.models import Address
from utils.baseview import BaseView


# Create your views here.
class OrderCheckView(BaseView):
    def get(self, request, username):
        user = request.myuser

        addresses = self.get_all_address(user.id)
        type = int(request.GET.get('settlement_type'))
        print(type, 'type')
        sku_list = self.get_all_sku_list(request, user, type)
        print(sku_list)

        result = {
            'code': 200,
            'data': {
                'addresses': addresses,
                'sku_list': sku_list
            },
            'base_url': settings.PIC_URL,
        }
        return JsonResponse(result)

    def get_all_address(self, user_id):
        all_address = Address.objects.filter(user_profile_id=user_id, is_deleted=False)
        # [{},{},...]
        addresses = []
        for address in all_address:
            addr_dict = {}
            addr_dict["id"] = address.id
            addr_dict["address"] = address.addr
            addr_dict["name"] = address.receiver
            addr_dict["mobile"] = address.receiver_mobile
            addr_dict["title"] = address.tag
            if address.is_default:
                addresses.insert(0, addr_dict)
            else:
                addresses.append(addr_dict)

        return addresses

    def get_all_sku_list(self, request, user, type):
        skus_list = []
        cartview = CartView()
        if type == 0:
            # 从购物车里跳到结算
            skus_list = cartview.get_redis_carts_list_data(user)
            # 筛选出选中状态为1的数据。
            skus_list = [sku for sku in skus_list if sku['selected'] == 1]

        else:
            sku_id = int(request.GET.get('sku_id'))
            buy_num = int(request.GET.get('buy_num'))
            if not all([sku_id, buy_num]):
                return JsonResponse({
                    'code': 400,
                    'error': 'sku_id and buy_num is required'
                })
            skus_list = cartview.get_mysql_carts_list_data(sku_id, buy_num)
        return skus_list


class OrderCreareView(BaseView):
    def post(self, request, username):
        user = request.myuser
        data = json.loads(request.body)
        address_id = data.get('address_id')
        if address_id is None:
            return JsonResponse({'code': 400, 'error': '缺少 address_id 参数'}, status=400)
        try:
            address_id = int(address_id)
        except ValueError:
            return JsonResponse({'code': 400, 'error': 'address_id 格式错误'}, status=400)
        type = int(data.get('settlement_type'))
        try:
            address = Address.objects.get(id=address_id, user_profile=user, is_deleted=False)
        except Address.DoesNotExist:
            return JsonResponse({
                'code': 400,
                'error': 'address_id is not exist'
            })
        total_count = 0
        total_amount = 0
        order_id = time.strftime("%Y%m%d%H%M%S") + str(user.id) + str(address_id)
        if type == 0:
            # 从购物车跳到结算,删除购物车数据
            with transaction.atomic():
                order = OrderInfo.objects.create(
                    order_id=order_id,
                    user=user,
                    address=address.addr,
                    total_count=total_count,
                    total_amount=total_amount,
                    pay_method=1,
                    status=1,
                    receiver_name=address.receiver,
                    receiver_mobile=address.receiver_mobile,

                )
                # 更新sku的库存和销量
                carts_dict = self.get_carts_dict(user)
                # for sku_id,count in carts_dict.items():
                #     sku=SKU.objects.get(id=sku_id)
                #     sku.stock -= count[0]
                #     sku.sales += count[0]
                #     sku.save()
                redis_conn = get_redis_connection("default")
                skus = SKU.objects.filter(id__in=carts_dict.keys())
                try:
                    # Process each SKU with distributed lock
                    for sku in skus:
                        lock_key = f"lock:sku:{sku.id}"
                        # Acquire lock with timeout (5 seconds)
                        with Lock(redis_conn, lock_key, timeout=5, blocking_timeout=2):
                            count = carts_dict[str(sku.id)][0]

                            # Refresh SKU from database to get latest values
                            sku = SKU.objects.get(id=sku.id)

                            if sku.stock < count:
                                raise Exception('库存不足')

                            # Update stock and sales atomically
                            SKU.objects.filter(id=sku.id).update(
                                stock=sku.stock - count,
                                sales=sku.sales + count
                            )

                            OrderGoods.objects.create(
                                order_info=order,
                                sku=sku,
                                count=count,
                                price=sku.price
                            )

                            total_amount += sku.price * count
                            total_count += count
                except Exception as e:
                    # Rollback changes if any exception occurs
                    transaction.set_rollback(True)
                    return JsonResponse({
                        'code': 400,
                        'error': str(e)
                    })
                order.total_amount = total_amount
                order.total_count = total_count
                order.save()


                #清除购物车中的数据
                CartView().del_cart_dict(user)
                print('清除购物车数据成功')

                result = {
                    'saller': '达达商城',
                    'total_amount': float(total_amount),
                    'order_id': order_id,
                    'pay_url': 'http://alipay.com/xxx/xx/'
                }
                return JsonResponse({
                    'code': 200,
                    'data': result
                })

            pass

    def get_carts_dict(self, user):

        return CartView().get_carts_dict(user)
        pass
